package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-25
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 入住申请
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        // 判断老人是否已入住
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
        queryWrapper.eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(elder)) {
            throw new RuntimeException("该老人已入住");
        }

        // 更新床位状态
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateBed(bed);

        // 新增或更新老人信息
        elder = insertOrUpdateElder(dto.getCheckInElderDto(), bed);

        // 新增签约办理
        insertContract(elder, dto);

        // 新增入住表
        CheckIn checkIn = insertCheckIn(elder, dto);

        // 新增入住配置
        insertCheckInConfig(checkIn, dto);


     /*   // 1、校验老人是否已入住
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<>();
        elderQueryWrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
        elderQueryWrapper.eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(elderQueryWrapper);
        if (ObjectUtils.isNotEmpty(elder)) {
            throw new RuntimeException("该老人已入住");
        }

        // 2、更新床位状态为已入住
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        // 3、新增或更新老人信息
        elder = insertOrUpdateElder(dto.getCheckInElderDto(), bed);

        // 4、新增签约办理
        insertContract(elder, dto);

        // 5、新增入住信息
        CheckIn checkIn = insertCheckIn(elder, dto);

        // 6、新增入住配置
        insertCheckInConfig(checkIn, dto);*/
    }

    /**
     * 新增入住配置
     * @param dto
     */
    private void insertCheckInConfig(CheckIn checkIn, CheckInApplyDto dto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     * @param dto
     */
    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto dto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);

        // 家属信息
        String familyString = JSON.toJSONString(dto.getElderFamilyDtoList());
        checkIn.setRemark(familyString);

        checkInMapper.insert(checkIn);

        return checkIn;
    }

    /**
     * 新增签约办理
     *
     * @param elder
     * @param dto
     */
    private void insertContract(Elder elder, CheckInApplyDto dto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        contract.setStartDate(startDate);
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setEndDate(endDate);

        // 判断合同状态
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(startDate)) {
            // 未生效
            contract.setStatus(0);
        } else if (now.isAfter(endDate)) {
            // 已过期
            contract.setStatus(2);
        } else {
            // 已生效
            contract.setStatus(1);
        }

        contractMapper.insert(contract);

    }

    /**
     * 新增或更新老人信息
     *
     * @param checkInElderDto
     * @param bed
     * @return
     */
    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());

        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        queryWrapper.eq(Elder::getStatus, 0);
        Elder elderTo = elderMapper.selectOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(elderTo)) {
            elder.setId(elderTo.getId());
            // 修改
            elderMapper.updateElder(elder);
        } else {
            // 新增
            elderMapper.insert(elder);
        }

        return elder;
    }

    /**
     * 入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo vo = new CheckInDetailVo();
        CheckIn checkIn = checkInMapper.selectById(id);

        // 获取老人id
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectById(elderId);
        if (ObjectUtils.isNotEmpty(elder)){
            BeanUtils.copyProperties(elder, checkInElderVo);
            int age = IdcardUtil.getAgeByIdCard(elder.getIdCardNo());
            checkInElderVo.setAge(age);
            vo.setCheckInElderVo(checkInElderVo);
        }

        // 获取家属信息
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(remark, ElderFamilyVo.class);
        vo.setElderFamilyVoList(elderFamilyVos);

        // 获取入住配置信息
        LambdaQueryWrapper<CheckInConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CheckInConfig::getCheckInId, checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapper);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        vo.setCheckInConfigVo(checkInConfigVo);

        // 签约办理
        LambdaQueryWrapper<Contract> qw = new LambdaQueryWrapper<>();
        qw.eq(Contract::getElderId, checkIn.getElderId());
        Contract contract = contractMapper.selectOne(qw);
        vo.setContract(contract);

        return vo;

       /* CheckInDetailVo vo = new CheckInDetailVo();
        CheckIn checkIn = checkInMapper.selectById(id);

        // 根据入住id获取老人信息
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());
        if (elder != null) {
            int age = IdcardUtil.getAgeByIdCard(elder.getIdCardNo());
            CheckInElderVo checkInElderVo = new CheckInElderVo();
            BeanUtils.copyProperties(elder, checkInElderVo);
            // 计算年龄
//            String birthday = elder.getBirthday();
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//            LocalDate localDate = LocalDate.parse(birthday, formatter);
//            Integer age = Math.toIntExact(ChronoUnit.YEARS.between(localDate, LocalDate.now()));
            checkInElderVo.setAge(age);
            vo.setCheckInElderVo(checkInElderVo);
        }

        // 根据入住id获取入住配置
        LambdaQueryWrapper<CheckInConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CheckInConfig::getCheckInId, checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapper);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        vo.setCheckInConfigVo(checkInConfigVo);

        // 根据入住id获取家属信息
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(remark, ElderFamilyVo.class);
        vo.setElderFamilyVoList(elderFamilyVos);

        // 根据入住id获取签约办理信息
        LambdaQueryWrapper<Contract> contractQueryWrapper = new LambdaQueryWrapper<>();
        contractQueryWrapper.eq(Contract::getElderId, checkIn.getElderId());
        Contract contract = contractMapper.selectOne(contractQueryWrapper);
        vo.setContract(contract);

        return vo;*/
    }

    /**
     * 新增入住配置
     *
     * @param checkIn 入住信息
     * @param dto     前端的所有数据
     */
//    private void insertCheckInConfig(CheckIn checkIn, CheckInApplyDto dto) {
//        CheckInConfig checkInConfig = new CheckInConfig();
//        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
//        checkInConfig.setCheckInId(checkIn.getId());
//
//        checkInConfigMapper.insert(checkInConfig);
//    }

    /**
     * 新增入住信息
     *
     * @param elder 老人信息
     * @param dto   前端的所有数据
     */
//    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto dto) {
//        CheckIn checkIn = new CheckIn();
//        checkIn.setElderName(elder.getName());
//        checkIn.setElderId(elder.getId());
//        checkIn.setIdCardNo(elder.getIdCardNo());
//        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
//        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
//        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
//        checkIn.setBedNumber(elder.getBedNumber());
//        checkIn.setStatus(0);
//
//        // 7、保存老人家属信息
//        // 老人家属信息只用于数据展示，转换成json字符串，存入checkIn表的remark字段中
//        String jsonString = JSON.toJSONString(dto.getElderFamilyDtoList());
//        checkIn.setRemark(jsonString);
//
//        checkInMapper.insert(checkIn);
//
//        return checkIn;
//    }

    /**
     * 新增签约办理
     *
     * @param elder 老人信息
     * @param dto   前端的所有数据
     */
//    private void insertContract(Elder elder, CheckInApplyDto dto) {
//        Contract contract = new Contract();
//        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
//        contract.setElderId(elder.getId());
//        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
//        contract.setElderName(elder.getName());
//
//        // 从入住配置中获取开启和结束时间
//        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
//        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
//
//        contract.setStartDate(startDate);
//        contract.setEndDate(endDate);
//
//        int status = startDate.isBefore(LocalDateTime.now()) ? 1 : 0;
//        contract.setStatus(status);
//
//        contractMapper.insert(contract);
//    }

    /**
     * 新增或更新老人信息
     *
     * @param checkInElderDto 老人数据
     * @param bed             床位数据
     */
//    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
//        Elder e = new Elder();
//        BeanUtils.copyProperties(checkInElderDto, e);
//        e.setBedId(bed.getId());
//        e.setBedNumber(bed.getBedNumber());
//        e.setStatus(1);
//
//        // 判断是新增还是修改
//        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<>();
//        elderQueryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
//        elderQueryWrapper.eq(Elder::getStatus, 0);
//        Elder elder = elderMapper.selectOne(elderQueryWrapper);
//
//        if (ObjectUtils.isNotEmpty(elder)) {
//            e.setId(elder.getId());
//            // 修改
//            elderMapper.updateById(e);
//        } else {
//            //新增
//            elderMapper.insert(e);
//        }
//
//        return e;
//    }

}
